package com.taotao.content.service.impl;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.util.JsonUtils;
import com.taotao.content.jedis.JedisClient;
import com.taotao.content.service.ContentService;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import java.util.Date;
import java.util.List;

@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    private JedisClient client;

    @Autowired
    private TbContentMapper mapper;

    @Value("${CONTENT_KEY}")
    private String CONTENT_KEY;









    @Override
    public TaotaoResult saveContent(TbContent tbContent) {
        tbContent.setCreated(new Date());
        tbContent.setUpdated(tbContent.getCreated());
        mapper.insertSelective(tbContent);
        //当添加内容的时候，需要清空此内容所属的分类下的所有的缓存
        try {
        client.hdel(CONTENT_KEY,tbContent.getCategoryId() +"");
            System.out.println("当插入的时候，清空缓存");
        }catch (Exception e){
            e.printStackTrace();
        }

        return TaotaoResult.ok();
    }

    @Override
    public List<TbContent> getContentListByCatId(Long categoryId) {
        //添加缓存不能影响正常的业务逻辑
        //判断 是否redis中有数据  如果有   直接从redis中获取数据 返回
        try {
            String  jsonstr = client.hget(CONTENT_KEY,categoryId+"");
            if(StringUtils.isNotBlank(jsonstr)){
                System.out.println("这里已经有缓存了");
                return JsonUtils.jsonToList(jsonstr,TbContent.class);
            }
        }catch (Exception e1){
            e1.printStackTrace();
        }

        TbContentExample example = new TbContentExample();
        example.createCriteria().andCategoryIdEqualTo(categoryId);
        List<TbContent> list = mapper.selectByExample(example);

        try {
            System.out.println("没有缓存");
            client.hset(CONTENT_KEY,categoryId+"",JsonUtils.objectToJson(list));
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
}
